﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.Configuration;

namespace LogHelper
{
    class Program
    {
        static readonly object locker = new object();

        static void Main(string[] args)
        {
            TestMultiThread();
        }

        static void TestSpeed()
        {
            Stopwatch sw = new Stopwatch();
            LogHandler logger = new LogHandler(@".");
            sw.Start();
            for (int i = 1; i < 1000; i++)
            {
                logger.WriteLine("test the performance of the class loghelper", LogLevel.Notice);
            }
            sw.Stop();
            Console.WriteLine($"time cost: {sw.ElapsedMilliseconds}");
        }

        static void TestMultiThread()
        {
            
            LogHandler logger = new LogHandler(@".");
            bool display = bool.Parse(ConfigurationManager.AppSettings["display"]);
            int threadNum = int.Parse(ConfigurationManager.AppSettings["threadNum"]);
            int loopNum = int.Parse(ConfigurationManager.AppSettings["loopNum"]);
            List<Thread> tdList = new List<Thread>();
            for(int i = 1; i<= threadNum; i++)
            {
                var t = new Thread(x => WriteLine(logger, loopNum, display));
                t.Name = $"thread {i}";
                tdList.Add(t);
            }
            foreach (var t in tdList)
            {
                t.Start();
            }
            WriteLine(logger, loopNum, display);
            foreach(var t in tdList)
            {
                t.Join();
            }
        }

        static void WriteLine(LogHandler log, int loopNum, bool isDisplay)
        {
            var name = Thread.CurrentThread.Name;
            if (name == null)
                name = "thread main";
            Stopwatch sw = new Stopwatch();
            for (int i=1; i<loopNum; i++)
            {
                sw.Reset();
                sw.Start();
                for(int j =0;j<2000;j++)
                {
                    double x = Math.Pow(12345654321, 0.0001);
                }
                sw.Stop();
                lock (locker)
                {
                    log.WriteLine($"test the multiThread of the class loghelper from {name}, elaps: {sw.ElapsedMilliseconds} millsec", LogLevel.Notice, isDisplay:isDisplay);
                }

            }
        }
    }
}
